#include "config.h"
#include "chooseapp.h"



//---------------------------------------
const QStringList Config::loadFilters ()
{
    QList<QByteArray> formats (QImageReader::supportedImageFormats ());

    QString filter1 ("Images (");
    foreach (QByteArray ba, formats) {
        filter1 += ba.prepend ("*.").append (' ');
    }
    filter1 += ')';
    QString filter2 (tr("Documents PDF (*.pdf)"));
    QString filter3 (tr ("Tous les fichiers (*)"));

    QStringList result;

    result << /*filter1 << filter2 <<*/ filter3;

    return result;
}
//---------------------------
const QString Config::saveFilters ()
{
    QList<QByteArray> formats (QImageWriter::supportedImageFormats ());

    QString filter ('(');
    foreach (QByteArray ba, formats)
        filter += ba.prepend ("*.").append (' ');

    filter += ')';
    return tr ("Images %1").arg (filter);
}
//---------------------------------------------------
const QString Config::scannedImageCompleteFileName ()
{
    QString path;

    if (optionAutoSaveScannedFiles ())
    {
        path = optionPathForScannedFiles ();
        QDir dir (path);
        if (dir.exists ())
            return path + baseNameFromScanner ();
    }
    return appWorkPath () + baseNameFromScanner ();
}
//-----------------------------------------------------
const QString Config::exportedTextCompleteFileName()
{
    Config c;
    QString name = c.optionExportTextToODF () ? tempODTBaseName () : tempTxtBaseName ();
    return appExportPath () + name;
}
//-----------------------------------------------------------
const QString Config::documentLinuxType (const QString &path)
{
    QString command (QString ("file -bi \"%1\"").arg (path));
    QString result (shell (command));
    return result;
}
//--------------------------------------------------
const QIcon Config::symbol (const QString &fileName)
{
    QString type (documentLinuxType (fileName));
    if (type.contains ("image"))
        return appIcon ();

    if (type.contains ("pdf"))
        return QIcon (":/images/gnome-mime-application-pdf.svg");

    return QIcon ();
}

//------------------------------------------
const QStringList Config::docPossiblePaths()
{
    return QStringList ()
            << "/usr/share/doc/solidROC/"
            << QApplication::applicationDirPath () + "/doc/"
               ;
}
//-----------------------------------------------
void Config::setOptionRestoreWorkSession (const bool b)
{
    setValue ("optionRestoreWorkSession", b);
}
//---------------------------------------------
bool Config::optionRestoreWorkSession () const
{
    return value ("optionRestoreWorkSession", true).toBool ();
}
//--------------------------------------
void Config::setOptionSimpleAnimation (const bool b)
{
    setValue ("optionSimpleAnimation", b);
}
//----------------------------
bool Config::optionSimpleAnimation () const
{
    return value ("optionSimpleAnimation", true).toBool ();
}
//---------------------------------
int Config::optionRecentFileMax () const
{
    return value ("optionRecentFileMax", 10).toInt ();
}
//-------------------------------------------
void Config::setOptionRecentFileMax(const int val)
{
    setValue ("optionRecentFileMax", val);
}
//-------------------------------------------
bool Config::optionRemoveTemp() const
{
    return value ("optionRemoveTempFiles", false).toBool ();
}
//-------------------------------------------
void Config::setOptionRemoveTemp(const bool b)
{
    setValue ("optionRemoveTempFiles", b);
}
//-------------------------------------------
bool Config::optionUseXSane() const
{
    return value ("optionUseXSane", false).toBool ();
}
//-------------------------------------------
void Config::setOptionUseXSane(const bool b)
{
    setValue ("optionUseXSane", b);
}
//----------------------------------
bool Config::optionAllSaneOptions () const
{
    return value ("optionAllSaneOptions", false).toBool ();
}
//-------------------------------------------
void Config::setOptionAllSaneOptions (const bool b)
{
    setValue ("optionAllSaneOptions", b);
}
//-----------------------------------------
QString Config::optionPathForScannedFiles() const
{
    return value ("optionPathForScannedFiles", defaultPathForScannedImages ()).toString ();
}
//---------------------------------------------------------
void Config::setOptionPathForScannedFiles(const QString &s)
{
    setValue ("optionPathForScannedFiles", s);
}
//----------------------------------------
bool Config::optionAutoSaveScannedFiles() const
{
    return value ("optionAutoSaveScannedFiles", false).toBool ();
}
//-----------------------------------------------------
void Config::setOptionAutoSaveScannedFiles(const bool b)
{
    setValue ("optionAutoSaveScannedFiles", b);
}
//---------------------------------
const QUrl Config::docFileUrl ()
{
    foreach (const QString& test, docPossiblePaths ())
    {
        QDir testDir (test);
        if (testDir.exists ()) {
            QString completePath (test + docFilename ());
            if (QFile (completePath).exists ()) {
                return QUrl::fromLocalFile (completePath);
            }
        }
    }
    return QUrl ();
}
//----------------------------------
int Config::optionMinPixNeighbours () const
{
    return value ("optionMinPixNeighbours", 1).toInt ();
}
//----------------------------------------------
void Config::setOptionMinPixNeighbours (const int val)
{
    setValue ("optionMinPixNeighbours", val);
}
//-------------------------------------------
bool Config::optionUsePdfToText () const
{
    return value ("optionUsePdfToText", false).toBool ();
}
//-------------------------------------------
void Config::setOptionUsePdfToText (const bool b)
{
    setValue ("optionUsePdfToText", b);
}
//------------------------------------
int Config::optionResolutionForPdf () const
{
    return value ("optionResolutionForPdf", 300).toInt ();
}
//-------------------------------------------
void Config::setOptionResolutionForPdf(const int d)
{
    setValue ("optionResolutionForPdf", d);
}
//---------------------------------
bool Config::optionDontAskForWP() const
{
    return value ("optionDontAskForWP", false).toBool ();
}
//---------------------------------
bool Config::optionAskForWP() const
{
    return not optionDontAskForWP ();
}
//---------------------------------
void Config::setOptionDontAskForWP (const bool b)
{
    setValue ("optionDontAskForWP", b);
}
//------------------------------------
int Config::optionWordProcessorIndex() const
{
    return value ("optionWordProcessorIndex", -1).toInt ();
}
//---------------------------------------------------
void Config::setOptionWordProcessorIndex (const int index)
{
    setValue ("optionWordProcessorIndex", index);
}
//--------------------------------------------------------
const QList<AppInfo> Config::wordProcessors ()
{
    return appsFromType ("wordprocessor", "Dicodor");
}
//-----------------------------------------------------------------------------------
const QList<AppInfo> Config::appsFromType (const QString& type, const QString& papajaacApp)
{
    // resultat = la liste des applis de ce type (nom + ligne de commande + icône)
    QList<AppInfo> result;

    AppInfo ppj;
    ppj.setName (tr ("%1 (intégré)").arg (papajaacApp));
    ppj.setIconPath (appIconPath ());

    result << ppj;

    const QString command (QString("grep -li \"^categories.*%1\" /usr/share/applications/*.desktop").arg (type));

    QStringList list (bash (command).split ("\n"));

    foreach (const QString& desktopFile, list) {
        QSettings desktopSettings (desktopFile, IniFormat);
        desktopSettings.beginGroup ("Desktop Entry");
        const QString& name (desktopSettings.value ("Name", QString ()).toString ());
        QString exec (desktopSettings.value ("Exec", QString ()).toString ());
        const QString& iconPath (desktopSettings.value ("Icon", QString ()).toString ());

        exec.replace ("%U", "%1", Qt::CaseInsensitive);
        if (!exec.contains ("%1")) exec += " %1";
        if (!name.isEmpty () && !exec.isEmpty ()) {
            AppInfo info;
            info.setName (name);
            info.setCommandLine (exec);
            info.setIconPath (iconPath);
            result << info;
        }
        desktopSettings.endGroup ();
    }

    return result;
}
//--------------------------------------------------
QString Config::shell (const QString& cmdLine)
{
    QProcess process;
    process.start (cmdLine);
    process.waitForFinished ();

    return (process.exitCode () == 0) ? QString (process.readAllStandardOutput ()) : QString ();
}
//------------------------------------------------------------
QString Config::bash (const QString &cmdLine)
{
    const QString effectiveCmdLine (QString ("bash -c \"%1\"").arg (cmdLine));

    return shell (effectiveCmdLine);
}
//---------------------------------------------
const QStringList Config::wordProcessorNames()
{
    QStringList result;
    foreach (const AppInfo &info, wordProcessors ()) {
        result << info.name ();
    }
    return result;
}
//--------------------------------------------------
QString Config::currentWordProcessorCommandLine ()
{
    return (wordProcessors ().at (optionWordProcessorIndex ())).commandLine ();
}
//--------------------------------
bool Config::optionCRBetweenROI () const
{
    return value ("optionCRBetweenROI", true).toBool ();
}
//----------------------------------------
void Config::setOptionCRBetweenROI(const bool b)
{
    setValue ("optionCRBetweenROI", b);
}
//-------------------------------
int Config::optionsToolboxPage() const
{
    return value ("optionsToolboxPage", 0).toInt ();
}
//----------------------------------------
void Config::setOptionsToolboxPage(const int p)
{
    setValue ("optionsToolboxPage", p);
}
//-------------------------------------
bool Config::optionRememberGeometry () const
{
    return value ("optionRememberGeometry", true).toBool ();
}
//---------------------------------------------
void Config::setOptionRememberGeometry (const bool b)
{
    setValue ("optionRememberGeometry", b);
}
//------------------------
QSize Config::windowSize () const
{
    return value ("windowSize", QSize (1051, 454)).toSize ();
}
//------------------------
QPoint Config::windowPos () const
{
    return value ("windowPos", QPoint (0, 0)).toPoint ();
}
//--------------------------------
bool Config::windowIsMaximized () const
{
    return value ("windowIsMaximized", false).toBool ();
}
//--------------------------------
bool Config::windowIsMinimized () const
{
    return value ("windowIsMinimized", false).toBool ();
}
//-------------------------------------------------------------------------------
void Config::setLastGeometry (const QPoint &p, const QSize &s, const bool maximized, const bool minimized)
{
    setValue ("windowPos", p);
    setValue ("windowSize", s);
    setValue ("windowIsMaximized", maximized);
    setValue ("windowIsMinimized", minimized);
}
//---------------------------------
QString Config::lastOpenDocPath () const
{
    return value ("lastOpenDocPath", "/tmp").toString ();
//				  QDesktopServices::storageLocation (QDesktopServices::PicturesLocation)).toString ();
}
//--------------------------------------------
void Config::setLastOpenDocPath (const QString &path)
{
    setValue ("lastOpenDocPath", path);
}
//---------------------------------------
QByteArray Config::lastSplitterState()
{
    return value ("lastSplitterState").toByteArray ();
}
//--------------------------------------------------------
void Config::setLastSplitterState(const QByteArray &ba)
{
    setValue ("lastSplitterState", ba);
}
//----------------------------------------
bool Config::optionInvertOrphanPixels() const
{
    return value ("optionInvertOrphanPixels", true).toBool ();
}
//----------------------------------------------
void Config::setOptionInvertOrphanPixels(const bool b)
{
    setValue ("optionInvertOrphanPixels", b);
}
//----------------------------------------
bool Config::optionExportTextToODF () const
{
    return ODFSupport () && value ("optionExportTextToODF", true).toBool ();
}
//----------------------------------------------
void Config::setOptionExportTextToODF (const bool b)
{
    setValue ("optionExportTextToODF", b);
}
//-------------------------------------------
void Config::setOptionRemoveCaesura(const bool b)
{
    setValue ("optionRemoveCaesura", b);
}
//--------------------------------
bool Config::optionRemoveCaesura () const
{
    return value ("optionRemoveCaesura", false).toBool ();
}
//--------------------------------------------
void Config::setOptionReplaceCRBySpace(const bool b)
{
    setValue ("optionReplaceCRBySpace", b);
}
//-----------------------------------
bool Config::optionReplaceCRBySpace() const
{
    return value ("optionReplaceCRBySpace", false).toBool ();
}

bool Config::optionInvertColors() const
{
    return value ("optionInvertColors", false).toBool ();
}
//}}} --------------------------------------------------------------------------
//{{{ .QFont Config::optionDefaultFont() const ----------------------------------

QFont Config::optionDefaultFont() const
{
    return value ("optionDefaultFont", QApplication::font ()).value<QFont> ();
}
//}}} --------------------------------------------------------------------------
//{{{ .QColor Config::optionUnderlineColor() const -----------------------------

QColor Config::optionUnderlineColor() const
{
    return value ("optionUnderlineColor", QColor (Qt::red)).value<QColor> ();
}

//}}} --------------------------------------------------------------------------
//{{{ .QColor Config::optionSaveFormat() const -----------------------------

QByteArray Config::optionSaveFormat () const
{
    return value ("optionSaveFormat", QByteArray ("plaintext")).value<QByteArray>();
}
//}}} --------------------------------------------------------------------------
//{{{ .void              setOptionDefaultFont(const QFont &font) ---------------

void Config::setOptionDefaultFont(const QFont &font)
{
    setValue ("optionDefaultFont", font);
}
//}}} --------------------------------------------------------------------------
//{{{ .void setOptionUnderlineColor(const QColor &color)-----------

void Config::setOptionUnderlineColor(const QColor &color)
{
    setValue ("optionUnderlineColor", color);
}

//}}} --------------------------------------------------------------------------
//{{{ .void              setOptionSaveFormat(const QString &format) -----------

void Config::setOptionSaveFormat(const QString &format)
{
    setValue ("optionSaveFormat", format.toUtf8 ());
}

void Config::setOptionInvertColors(const bool b)
{
    setValue ("optionInvertColors", b);
}
